﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

using XRpgLibrary.TileEngine;
using XRpgLibrary;

namespace SourceOfMagic.Components
{
    public class FpsComponent : DrawableGameComponent, IGameDrawableMenu, IGameUpdateableMenu
    {
        #region Fields

        SourceOfMagicGame GameRef;

        #endregion

        #region Properties
        public bool IsAlive { get; set; }
        public static float Fps { get; set; }
        static float TotalFrames { get; set; }
        static float ElapsedTime { get; set; }
        static SpriteFont Font { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Creates a component that can draw the games current FPS
        /// </summary>
        /// <param name="game"></param>
        /// <param name="spriteBatch"></param>
        /// <param name="font"></param>
        public FpsComponent(SourceOfMagicGame game, SpriteFont font)
            : base(game)
        {
            GameRef = game;

            Font = font;
            Fps = 0;
            TotalFrames = 0;
            ElapsedTime = 0;

            IsAlive = true;
            Enabled = true;
        }

        #endregion

        #region XNA Methods

        public override void Update(GameTime gameTime)
        {
            if (Enabled)
            {
                ElapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;

                TotalFrames++;

                if (ElapsedTime > 1.0f)
                {
                    Fps = TotalFrames;
                    TotalFrames = 0;
                    ElapsedTime = 0;
                }
            }

            if (InputHandler.KeyReleased(GameCommands.ActivateDebugHUD))
                Toggle(); 

            base.Update(gameTime);
        }

        private void Toggle()
        {
            Enabled = !Enabled;
        }

        public override void Draw(GameTime gameTime)
        {
            Draw(gameTime, null);
        }

        public void Draw(GameTime gameTime, Camera camera)
        {
            if (Visible && Enabled)
            {
                GameRef.spriteBatch.DrawString(Font, Fps.ToString(),
                    new Vector2(
                        10,
                        Game.GraphicsDevice.Viewport.Height - Font.LineSpacing),
                    Color.White);
            }

            base.Draw(gameTime);
        }

        #endregion
    }
}